//
//  HTPremiumGuideScreen.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/22.
//

import SwiftUI

struct HTPremiumGuideScreen: View {

  @EnvironmentObject private var var_store: HTAppStore
  @State var var_adConfig: HTAdConfig? = HTAdConfig()
  @State var var_onClose: (() -> Void)? = {}
  @State var var_onChooseMore: (() -> Void)? = {}
  @State var var_showHoliday: Bool = false
  @State var var_introductorySub: HTSubscribe? = HTSubscribe()

  var body: some View {
    VStack{
      if (var_showHoliday) {
        HTPremiumHolidayGuide(var_adConfig: $var_adConfig, var_introductorySub: $var_introductorySub, var_onClose: var_onClose, var_onChooseMore: var_onChooseMore) { sub in
          ht_pay(sub: sub)
        }
      } else {
        HTPremiumRegularGuide(var_adConfig: $var_adConfig, var_introductorySub: $var_introductorySub, var_onClose: var_onClose, var_onChooseMore: var_onChooseMore) { sub in
          ht_pay(sub: sub)
        }
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .ignoresSafeArea()
    .onAppear{
      let var_adConfigs = HTCoreDataManager().ht_fetchAdConfigData()
      if let var_adConfig_first = var_adConfigs.first {
        if (var_adConfig?.ht_holidaySubStatus() == true) {
          var_showHoliday = true
        }
        var_adConfig = HTAdConfig.deserialize(from: var_adConfig_first.config)!
      }
      var_introductorySub = var_store.state.var_subscribeState.var_introductorySubscribe!
      HTNetworkManager().ht_requestForBuried(.htEnumVipSh(var_source: "14"))
    }
    .onReceive(var_store.objectWillChange) { state in
      var_introductorySub = var_store.state.var_subscribeState.var_introductorySubscribe!
    }
  }

  func ht_pay(sub: HTSubscribe) {
    var_store.dispatch(HTEnumSubscribeAction.ht_purchaseProduct(productId: sub.var_productIdentifier ?? "", andSuccess: {
      var_onClose!()
    }, andFail: nil))
  }
}
